<?php
/**
 * Created by PhpStorm.
 * User: lengbin
 * Date: 2018/6/21
 * Time: 下午4:22
 */

namespace common\core\actions;

use common\core\base\Action;
use common\helpers\Html;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * create / update
 *
 * Class UpdateAction
 * @package common\core\actions
 */
class UpdateAction extends Action
{
    /**
     *  call_user_func
     * @var string
     */
    public $update;

    /**
     * is redirect
     *
     * @var bool
     */
    public $isJump;

    /**
     * delete filed name
     *
     * @var string
     */
    public $isDeleteName = 'is_delete';

    /**
     *  validate filed
     *
     * @var array
     */
    public $validateFiled;

    /**
     * is ajax validate
     * @var bool
     */
    public $isAjax;

    public function init()
    {
        parent::init();

        if ($this->isJump === null) {
            $this->isJump = false;
        }

        if ($this->isAjax === null) {
            $this->isAjax = false;
        }
    }

    public function run()
    {
        $this->isPost();
        $params = \Yii::$app->request->post();

        if (!empty($this->modelClass)) {
            $this->modelClass->scenario = $this->scenario;
        }
        // ajax 提交得为 前端 ajax表单验证
        // or update
        if (\Yii::$app->request->isAjax) {
            if (!empty($this->modelClass)) {
                $model = $this->modelClass->updateByParams($params, $this->isAjax, $this->isDeleteName);
            } else {
                if ($this->update instanceof \Closure) {
                    $model = call_user_func($this->update, $params);
                }
            }
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        try {
            if ($this->update instanceof \Closure) {
                $model = call_user_func($this->update, $params);
            } else {
                $model = $this->modelClass->updateByParams($params, true, $this->isDeleteName);
            }
            if ($this->isJump) {
                // if return model
                if (is_object($model)) {
                    $model->validate($this->validateFiled) ? $this->successAlert() : $this->errorAlert($this->getError($model));
                } else {
                    $model ? $this->errorAlert($model) : $this->successAlert();
                }
                return $this->redirect();
            }

            if ($model->validate($this->validateFiled)) {
                $this->successAlert();
                return $this->redirect();
            }

        } catch (\Exception $exception) {
            $str = str_replace(PHP_EOL, '', Html::encode($exception->getMessage()));
            $this->errorAlert($str);
            return $this->redirect();
        }
        return $this->controller->render($this->view, $this->getData($model));
    }
}